package com.xiaouyudeguang.common.utils;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    public static Authentication getAuthentication() throws Exception {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return securityContext == null ? null : securityContext.getAuthentication();
    }

    public static MapModel<String, Object> getPrincipal() throws Exception {
        Authentication authentication = getAuthentication();
        return authentication == null ? MapModel.empty() : JsonObject.toMap(authentication.getPrincipal());
    }

    public static String getUserId() throws Exception {
        Authentication authentication = getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return null;
        }
        return getPrincipal().getText("id");
    }

    public static String getName() throws Exception {
        Authentication authentication = getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return EnvironmentUtils.getNamespace();
        }
        return getPrincipal().getText("name");
    }

    public static String getAccount() throws Exception {
        Authentication authentication = getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return EnvironmentUtils.getNamespace();
        }
        return getPrincipal().getText("username");
    }

    public static String getPhone() throws Exception {
        Authentication authentication = getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return EnvironmentUtils.getNamespace();
        }
        return getPrincipal().getText("phone");
    }
}
